//
//  YLAStroeViewControll.swift
//  Your Lover AI
//
//  Created by 阿忠 on 2024/6/26.
//

import Foundation
import UIKit
import SwiftyStoreKit
import StoreKit


class YLAStroeViewControll: UIViewController, UITableViewDataSource,UITableViewDelegate,YLAStroeCell.CellDelegate{
    
    var title_lb: UILabel!      // 标题
    var tableView : UITableView!
    private let AncientBookCellID = "YLAStroeCell"
    
    var sourceVc = "back" //用了判断页面来源
    
    lazy var bgImg: UIImageView = {
        let image = UIImageView(image: UIImage(named: "bg"))
        return image
    }()
    
    lazy var backBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.backgroundColor = .clear
        button.setImage(UIImage(named: "icon_left"), for: UIControl.State.normal)
        button.addTarget(self, action: #selector(backClick), for: .touchUpInside)
        return button
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.red
        self.navigationController?.interactivePopGestureRecognizer!.isEnabled = false
        
        setUI()
        
        
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBarController!.tabBar.isHidden = true
        self.navigationController?.navigationBar.isHidden = true
    }
    
    func setUI() {
        
        view.addSubview(bgImg)
        bgImg.snp.makeConstraints { make in
            make.left.top.bottom.right.equalToSuperview()
        }
        
        view.addSubview(backBtn)
        backBtn.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.top.equalTo(50)
            make.width.height.equalTo(32)
        }
        
        tableView = UITableView()
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(100)
            make.bottom.equalTo(30)
        }
        view.addSubview(tableView)
        tableView.dataSource = self
        tableView.delegate = self
        extendedLayoutIncludesOpaqueBars = true;
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false;
        };
        
        tableView.reloadData()
        
    }
    
    
    
    //MARK: UITableViewDataSource
    // cell的个数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    // UITableViewCell
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellid = "testCellID"
        var cell:YLAStroeCell? = tableView.dequeueReusableCell(withIdentifier: cellid) as? YLAStroeCell
        if cell==nil {
            cell = YLAStroeCell(style:.subtitle, reuseIdentifier: cellid)
            cell?.delegate = self
            
        }
        cell?.backgroundColor = .clear
        cell?.selectionStyle = .none
        
        return cell!
    }
    
    //MARK: UITableViewDelegate
    // 设置cell高度
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 1300
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 20
    }
    // 选中cell后执行此方法
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        print("------选中了chat的cell------")
        
    }
    
    func cell(_ cell: YLAStroeCell, toher1: Any) {
        print(toher1)
        var price_str = YLAPriceDate().Lift
        if toher1 as! String == "lift" {
            price_str = YLAPriceDate().Lift
        }else if toher1 as! String == "year" {
            price_str = YLAPriceDate().Year
        }else if toher1 as! String == "week" {
            price_str = YLAPriceDate().Week
        }else if toher1 as! String == "privacy" {
            let webvc = YLAWebViewController()
            webvc.urlWeb = "https://yourloverai.xyz/yourloverai-privacy.html"
            webvc.titleWeb = "Privacy Policy"
            self.navigationController?.pushViewController(webvc, animated: true)
            return
        }else if toher1 as! String == "terms" {
            let webvc = YLAWebViewController()
            webvc.urlWeb = "https://www.yourloverai.xyz/yourloverai-terms.html"
            webvc.titleWeb = "Terms"
            self.navigationController?.pushViewController(webvc, animated: true)
            return
        }else if toher1 as! String == "renstor" {
            self.renstorSet()
            return
        }
        
        SwiftyStoreKit.purchaseProduct(price_str, quantity: 1, atomically: false) { [self] result in
            switch result {
            case .success(let product):
                // fetch content from your server, then:
                if product.needsFinishTransaction {
                    SwiftyStoreKit.finishTransaction(product.transaction)
                }
                
                if product.productId == "com.nexthinks.yourloverai.vip001" {
                    self.verifyPurchase(product.productId)
                }else{
                    self.validateReceipt([product.productId])
                }
                
                print("Purchase Success: \(product.productId)")
                
                //            case .error(let error):
                //                switch error.code {
                //                case .unknown: print("Unknown error. Please contact support")
                //                case .clientInvalid: print("Not allowed to make the payment")
                //                case .paymentCancelled: break
                //                case .paymentInvalid: print("The purchase identifier was invalid")
                //                case .paymentNotAllowed: print("The device is not allowed to make the payment")
                //                case .storeProductNotAvailable: print("The product is not available in the current storefront")
                //                case .cloudServicePermissionDenied: print("Access to cloud service information is not allowed")
                //                case .cloudServiceNetworkConnectionFailed: print("Could not connect to the network")
                //                case .cloudServiceRevoked: print("User has revoked permission to use this cloud service")
                //                default: print((error as NSError).localizedDescription)
                //                }
                //
            case .error(let error):
                print("Purchase Failed: \(error)")
                switch error.code {
                case .unknown:
                    showAlert(alertWithTitle("Purchase failed", message: error.localizedDescription))
                case .clientInvalid: // client is not allowed to issue the request, etc.
                    showAlert(alertWithTitle("Purchase failed", message: "Not allowed to make the payment"))
                case .paymentCancelled: // user cancelled the request, etc.
                    print("")
                case .paymentInvalid: // purchase identifier was invalid, etc.
                    showAlert(alertWithTitle("Purchase failed", message: "The purchase identifier was invalid"))
                case .paymentNotAllowed: // this device is not allowed to make the payment
                    showAlert(alertWithTitle("Purchase failed", message: "The device is not allowed to make the payment"))
                case .storeProductNotAvailable: // Product is not available in the current storefront
                    showAlert(alertWithTitle("Purchase failed", message: "The product is not available in the current storefront"))
                case .cloudServicePermissionDenied: // user has not allowed access to cloud service information
                    showAlert(alertWithTitle("Purchase failed", message: "Access to cloud service information is not allowed"))
                case .cloudServiceNetworkConnectionFailed: // the device could not connect to the nework
                    showAlert(alertWithTitle("Purchase failed", message: "Could not connect to the network"))
                case .cloudServiceRevoked: // user has revoked permission to use this cloud service
                    showAlert(alertWithTitle("Purchase failed", message: "Cloud service was revoked"))
                default:
                    showAlert(alertWithTitle("Purchase failed", message: (error as NSError).localizedDescription))
                }
            }
            
        }
    }
    
    //一次性买断校验
    func verifyPurchase(_ productId: String) {
        
        let appleValidator = AppleReceiptValidator(service: .production, sharedSecret: "ad1b36f7462843a0be8aee1da39b1b4a")
        SwiftyStoreKit.verifyReceipt(using: appleValidator) { result in
            
            switch result {
            case .success(let receipt):
                let purchaseResult = SwiftyStoreKit.verifyPurchase(
                    productId: productId,
                    inReceipt: receipt)
                self.alertForVerifyPurchase(purchaseResult, productId: productId)
            case .error:
                self.showAlert(self.alertForVerifyReceipt(result))
            }
        }
    }
    
    
    //订阅校验
    func validateReceipt(_ productIds: Set<String>) {
        let appleValidator = AppleReceiptValidator(service: .production, sharedSecret: "ad1b36f7462843a0be8aee1da39b1b4a")
        SwiftyStoreKit.verifyReceipt(using: appleValidator) { result in
            
            switch result {
            case .success(let receipt):
                let purchaseResult = SwiftyStoreKit.verifySubscriptions(productIds: productIds, inReceipt: receipt)
                self.alertForVerifySubscriptions(purchaseResult, productIds: productIds)
            case .error:
                self.showAlert(self.alertForVerifyReceipt(result))
            }
        }
    }
    
    
    
    
    //恢复购买
    func renstorSet(){
        SwiftyStoreKit.restorePurchases(atomically: false) { results in
            if results.restoreFailedPurchases.count > 0 {
                print("Restore Failed: \(results.restoreFailedPurchases)")
                self.showAlert(self.alertWithTitle("Restore failed", message: "Unknown error. Please contact support"))
            }
            else if results.restoredPurchases.count > 0 {
                
                for purchase in results.restoredPurchases {
                    if purchase.needsFinishTransaction {
                        SwiftyStoreKit.finishTransaction(purchase.transaction)
                    }
                    // 处理每个恢复的购买项目
                    self.handleRestoredPurchase(purchase)
                }
                print("Restore Success: \(results.restoredPurchases)")
                
            }else {
                
                UserDefaults.standard.set(false, forKey: "life")
                UserDefaults.standard.set(false, forKey: "year")
                UserDefaults.standard.set(false, forKey: "week")
                
                print("Nothing to Restore")
                self.showAlert(self.alertWithTitle("Nothing to restore", message: "No previous purchases were found"))
            }
        }
    }
    
    
    func handleRestoredPurchase(_ purchase: Purchase) {
        let productId = purchase.productId
        print("Restored Purchase: \(productId)")
        
        // 根据 productId 确定是订阅还是非消耗型产品
        if isSubscription(productId: productId) {
            // 处理订阅恢复
            print("Restored Subscription: \(productId)")
            restoreSubscription(purchase)
        } else {
            // 处理非消耗型产品恢复
            print("Restored Consumable or Non-Consumable Product: \(productId)")
            unlockNonConsumableContent(purchase)
        }
    }

    func isSubscription(productId: String) -> Bool {
        // 判断是否为订阅产品，通常根据产品ID的命名规则
        let subscriptionProductIds: Set<String> = ["com.aichat.yourloverai.ailoveryour.yearly001","com.nexthinks.yourloverai.weekly001"]
        return subscriptionProductIds.contains(productId)
    }

    func restoreSubscription(_ purchase: Purchase) {
        // 恢复订阅内容或状态
        print("Restoring subscription for product: \(purchase.productId)")
        // 根据你的业务逻辑处理订阅恢复
        self.validateReceipt([purchase.productId])
    }

    func unlockNonConsumableContent(_ purchase: Purchase) {
        // 解锁用户已经购买的非消耗型产品内容
        print("Unlocking content for product: \(purchase.productId)")
        // 根据你的业务逻辑解锁相应的内容
        self.verifyPurchase(purchase.productId)
    }
    
    
    
    //成功
    func alertForVerifySubscriptions(_ result: VerifySubscriptionResult, productIds: Set<String>) -> Void {
        
        /*
         UserDefaults.standard.set(true, forKey: "life")
         UserDefaults.standard.set(true, forKey: "year")
         UserDefaults.standard.set(true, forKey: "week")
         */
        
        switch result {
        case .purchased(let expiryDate, let items):
            
            //购买成功  存储标识符
            
            if items.first?.productId == "com.nexthinks.yourloverai.yearly001" {
                UserDefaults.standard.set(true, forKey: "year")
            }else{
                UserDefaults.standard.set(true, forKey: "week")
            }
           
            print("\(productIds) is valid until \(expiryDate)\n\(items)\n")
            //            return nil
            //产品有效期至
            self.showAlert(self.alertWithTitle("Product is purchased", message: "Product is valid until \(expiryDate)"))
        case .expired(let expiryDate, let items):
            print("\(productIds) is expired since \(expiryDate)\n\(items)\n")
            
            //到期  存储标识符
            if items.first?.productId == "com.nexthinks.yourloverai.yearly001" {
                UserDefaults.standard.set(false, forKey: "year")
            }else{
                UserDefaults.standard.set(false, forKey: "week")
            }
//            self.showAlert(self.alertWithTitle("Product expired", message: "Product is expired since \(expiryDate)"))
        case .notPurchased:
            
            //到期  存储标识符
            
            print("\(productIds) has never been purchased")
//            return alertWithTitle("Not purchased", message: "This product has never been purchased")
        }
    }
    
    //订阅
    func alertForVerifyReceipt(_ result: VerifyReceiptResult) -> UIAlertController {
        
        switch result {
        case .success(let receipt):
            print("Verify receipt Success: \(receipt)")
            return alertWithTitle("Receipt verified", message: "Receipt verified remotely")
        case .error(let error):
            print("Verify receipt Failed: \(error)")
            switch error {
            case .noReceiptData:
                return alertWithTitle("Receipt verification", message: "No receipt data. Try again.")
            case .networkError(let error):
                return alertWithTitle("Receipt verification", message: "Network error while verifying receipt: \(error)")
            default:
                return alertWithTitle("Receipt verification", message: "Receipt verification failed: \(error)")
            }
        }
    }
    
    //固定商品一次性买断
    func alertForVerifyPurchase(_ result: VerifyPurchaseResult, productId: String) -> Void {
        
        /*
         UserDefaults.standard.set(true, forKey: "life")
         UserDefaults.standard.set(true, forKey: "year")
         UserDefaults.standard.set(true, forKey: "week")
         */
        
        switch result {
        case .purchased:
            
            UserDefaults.standard.set(true, forKey: "life")
            
            print("\(productId) is purchased")
            self.showAlert(self.alertWithTitle("Product is purchased", message: "Product will not expire"))
        case .notPurchased:
            
            UserDefaults.standard.set(false, forKey: "life")
            
            print("\(productId) has never been purchased")
//            return alertWithTitle("Not purchased", message: "This product has never been purchased")
        }
    }
    

    
    @objc func backClick(){
        if sourceVc == "store"{//开屏流程进来的  去主页
            let homeVc = YLAHomeViewController()
            let nav_1 = UINavigationController(rootViewController: homeVc)
            var image:UIImage = UIImage(named: "tabbar_home_s")!
            var selectedimage:UIImage = UIImage(named: "tabbar_home_u")!
            image = image.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
            selectedimage = selectedimage.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
            nav_1.tabBarItem = UITabBarItem(title: "Home", image: selectedimage, selectedImage: image)
            
            let appforVc = YLAListViewController()
            let nav_2 = UINavigationController(rootViewController: appforVc)
            var image_2:UIImage = UIImage(named: "tabbar_chat_u")!
            var selectedimage_2:UIImage = UIImage(named: "tabbar_chat_s")!
            image_2 = image_2.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
            selectedimage_2 = selectedimage_2.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
            nav_2.tabBarItem = UITabBarItem(title: "Chat", image: image_2, selectedImage: selectedimage_2)
            
            let setVc = YLAMyViewController()
            let nav_3 = UINavigationController(rootViewController: setVc)
            var image_3:UIImage = UIImage(named: "tabbar_me_u")!
            var selectedimage_3:UIImage = UIImage(named: "tabbar_me_s")!
            image_3 = image_3.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
            selectedimage_3 = selectedimage_3.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
            nav_3.tabBarItem = UITabBarItem(title: "Me", image: image_3, selectedImage: selectedimage_3)
            
            // 全局设置TabBarItem的标题文字颜色（可选）
            self.tabBarController!.tabBar.tintColor = UIColor.white
            
            self.tabBarController!.tabBar.unselectedItemTintColor = UIColor(hex: "D36AF0")
            
            self.tabBarController!.viewControllers = [nav_1, nav_2, nav_3]
            
        }else{
            self.navigationController?.popViewController(animated: true)
        }
        
    }
    
    func showAlert(_ alert: UIAlertController) {
        guard self.presentedViewController != nil else {
            self.present(alert, animated: true, completion: nil)
            return
        }
    }
    
    func alertWithTitle(_ title: String, message: String) -> UIAlertController {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
        return alert
    }
}
